<?php
/*
 * This file is part of the BooXtore Student project.
 *
 * (c) Francis Backeland f.backeland@gmail.com
 * (c) Laurine Chaplot chaplot.laurine@orange.fr
 * (c) Julien Dutot julien.dutot@gmail.com
 * (c) Romain Guillaume romain-guillaume@orange.fr
 * (c) Guillaume Paringaux g.paringaux@gmail.com
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code
 * 
 */

namespace BXTR\AdminBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

/**
 * Class AdminEditForm
 */
class AdminEditForm extends AbstractAdminForm
{
    protected $em;

    public function __construct($em)
    {
        $this->em = $em;
    }

    public function buildControls(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('save', 'save_button')
            ->add('back', 'back_button', array(
                'url' => $options['back_url']
            ));
    }

    protected function getEntityMetadata($class)
    {
        return $this->em->getClassMetadata($class);
    }

    protected function getFieldNames($class)
    {
        return $this->getEntityMetadata($class)->fieldNames;
    }

    public function buildBody(FormBuilderInterface $builder, array $options)
    {
        $fieldList = $options['fields']; 

        foreach($fieldList as $name => $params) {
            $opt = array();
            if (in_array($params['visibility'], array('edit', 'both'))) {
                if (array_key_exists('options', $params) ) {
                    $opt = $params['options'];
                }
                $opt['label'] = $params['label'];
                $this->buildField($builder, $name, $params['type'], $opt);
            }
        }
    }

    protected function buildField(FormBuilderInterface $builder, $fieldName, $fieldType=null, $fieldOptions=array())
    {
        $builder->add($fieldName, $fieldType, $fieldOptions);
    } 

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'query_builder' => null,
        ));

        $resolver->setRequired(array(
            'fields',
            'class', // String entity repository name
            'back_url',
        ));
    }

    public function getName()
    {
        return 'bxtr_admin_edit';
    }
}
